package repositories

import (
	"fmt"
	"pegasus/models"
	"pegasus/utils"

	"github.com/go-xorm/xorm"
)

//UserRepo 用户表的操作
type UserRepo struct {
	logger utils.ILogger
	engine *xorm.Engine
}

//NewUserRepo 构造UserRepo
func NewUserRepo(il utils.ILogger, e *xorm.Engine) *UserRepo {
	return &UserRepo{
		logger: il,
		engine: e,
	}
}

//Register 用户注册
func (ur *UserRepo) Register(user, password string) error {
	return utils.Transaction(ur.engine, func(si *xorm.Session) error {
		bean := &models.UserBean{User: user}
		found, err := si.Get(bean)
		if err != nil {
			return err
		}
		if found {
			return fmt.Errorf("用户已存在 %s", user)
		}
		bean.Password = hash(password)
		var a int64
		a, err = si.Insert(bean)
		moneybean := &models.MoneyBean{UserId: a}
		_, err = si.Insert(moneybean)
		userinfo := &models.UserInfoBean{}
		userinfo.UserId = a
		_, err = si.Insert(userinfo)
		return err
	})
}

//Find 根据User查找bean
func (ur *UserRepo) Find(user string) *models.UserBean {
	bean := &models.UserBean{User: user}
	var found bool
	var err error
	utils.Transaction(ur.engine, func(si *xorm.Session) error {
		found, err = si.Get(bean)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil || !found {
		return nil
	}
	return bean
}

//CheckPassword 验证密码 error 为nil则验证通过
func (ur *UserRepo) CheckPassword(beanPassword, password string) bool {
	return hash(password) == beanPassword
}

//UpdatePassword 修改帐号密码
func (ur *UserRepo) UpdatePassword(userID int64, oldPassword, newPassword string) error {
	return utils.Transaction(ur.engine, func(si *xorm.Session) error {
		bean := &models.UserBean{}
		found, err := si.ID(userID).Get(bean)
		if err != nil {
			return err
		}
		if !found || !ur.CheckPassword(bean.Password, oldPassword) {
			return fmt.Errorf("帐号或密码错误")
		}
		bean.Password = hash(newPassword)
		_, err = si.ID(bean.ID).Cols("Password").Update(bean)
		//_, err = si.Update(&models.UserBean{Password: hash(newPassword)}, bean)
		//_, err = si.Exec("UPDATE `user_bean` SET `password` = ?, `version` = `version` + 1 WHERE `i_d`=? AND `user`=? AND `password`=? AND `version`=?",
		//hash(newPassword), bean.ID, bean.User, bean.Password, bean.Version)
		return err
	})
}

func hash(password string) string {
	return password
}
